﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace DynamicToSql
{
    public interface ITransaction : IDisposable
    {
        void Commit();

        void Rollback();
        
        TransactionState State { get; }
        
        IDbTransaction InnerTransaction { get; }
    }

    internal sealed class Transaction : ITransaction
    {
        private bool disposed;

        private Transaction()
        { 
        
        }

        internal Transaction(IDbTransaction transaction)
        {
            State = TransactionState.New;
            InnerTransaction = transaction;
        }

        ~Transaction()
        {
            Dispose(false);
        }

        public void Commit()
        {
            if (State == TransactionState.New)
            {
                InnerTransaction.Commit();
                State = TransactionState.Committed;
            }
        }

        public void Rollback()
        {
            if (State == TransactionState.New)
            {
                InnerTransaction.Rollback();
                State = TransactionState.Rolledback;
            }
        }

        public void Dispose()
        {
            Dispose(true);

            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (State == TransactionState.New)
                        InnerTransaction.Rollback();

                    InnerTransaction.Dispose();

                    State = TransactionState.Disposed;
                    InnerTransaction = null;
                }

            }

            disposed = true;
        }

        public TransactionState State { get; private set; }

        public IDbTransaction InnerTransaction { get; private set; }
    }
}
